package com.winhxd.b2c.product.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.customer.condition.DistributorChannelTypeCondition;
import com.winhxd.b2c.common.domain.customer.vo.CustomerDistributorChannelTypeVO;
import com.winhxd.b2c.common.domain.product.condition.ProductPriceProgramAddCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductPriceProgramAddDetailCondition;
import com.winhxd.b2c.common.domain.product.condition.ProductPriceProgramCondition;
import com.winhxd.b2c.common.domain.product.model.*;
import com.winhxd.b2c.common.domain.product.vo.ProductPriceProgramDetailVO;
import com.winhxd.b2c.common.domain.product.vo.ProductPriceProgramWithSpuVO;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.CustomerServiceClient;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.product.dao.*;
import com.winhxd.b2c.product.service.ProductPriceProgramService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * @author luosixiang
 */
@Service
public class ProductPriceProgramServiceImpl implements ProductPriceProgramService {

    private static final Logger logger = LoggerFactory.getLogger(ProductPriceProgramServiceImpl.class);

    @Autowired
    private ProductPriceProgramMapper productPriceProgramMapper;
    @Autowired
    private ProductSkuMapper productSkuMapper;
    @Autowired
    private ProductSpuMapper productSpuMapper;
    @Autowired
    private ProductPriceSpuMapper productPriceSpuMapper;
    @Autowired
    private ProductPriceSkuMapper productPriceSkuMapper;
    @Autowired
    private CustomerServiceClient customerServiceClient;

    @Override
    public List<ProductPriceProgram> findAllProductPriceProgram() {
        return productPriceProgramMapper.selectAll();
    }

    @Override
    public List<ProductPriceProgram> findProductPriceProgramByModel(ProductPriceProgramCondition condition) {
        logger.info("findProductPriceProgramByModel方法入参是："+JsonUtil.toJSONString(condition));
        ProductPriceProgram productPriceProgram = new ProductPriceProgram();
        BeanUtils.copyProperties(condition, productPriceProgram);
        return productPriceProgramMapper.selectByModel(productPriceProgram);
    }

    @Override
    public PagedList<ProductPriceProgram> findProductPriceProgramPageByModel(ProductPriceProgramCondition condition) {
        logger.info("findProductPriceProgramPageByModel方法入参是：" + JsonUtil.toJSONString(condition));
        ProductPriceProgram productPriceProgram = new ProductPriceProgram();
        BeanUtils.copyProperties(condition, productPriceProgram);
        List<ProductPriceProgram> productPricePrograms = productPriceProgramMapper.selectByModel(productPriceProgram);
        Page page = PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        PagedList<ProductPriceProgram> pagedList = new PagedList<>();
        pagedList.setData(productPricePrograms);
        pagedList.setPageNo(condition.getPageNo());
        pagedList.setPageSize(condition.getPageSize());
        pagedList.setTotalRows(page.getTotal());
        return pagedList;
    }

    @Override
    public ProductPriceProgramWithSpuVO findProductPriceProgramDetail(ProductPriceProgramAddDetailCondition condition) {
        logger.info("findProductPriceProgramDetail方法入参是" + JsonUtil.toJSONString(condition));
        ProductPriceProgramWithSpuVO vo = new ProductPriceProgramWithSpuVO();
        if(condition.getId() != null){
            // 根据价格方案id查询价格方案信息
            ProductPriceProgram productPriceProgram = productPriceProgramMapper.selectByPrimaryKey(condition.getId());
            if(productPriceProgram == null){
                throw new BusinessException(BusinessCode.CODE_880400);
            }
            vo.setId(productPriceProgram.getId());
            vo.setName(productPriceProgram.getName());
            vo.setBrandId(productPriceProgram.getBrandId());
            // 根据条件查询价格方案及spu详情
            List<ProductPriceProgramDetailVO> list = productPriceProgramMapper.selectProductPriceProgramDetail(condition);
            list.stream().forEach(priceProgram ->{
                BigDecimal zero = BigDecimal.ZERO;
                if(priceProgram.getFirstPoint() == null){
                    priceProgram.setFirstPoint(0);
                }
                if(priceProgram.getSecondPoint() == null){
                    priceProgram.setSecondPoint(0);
                }
                if(priceProgram.getMemberPoint() == null){
                    priceProgram.setMemberPoint(0);
                }
                if(priceProgram.getFirstIncome() == null){
                    priceProgram.setFirstIncome(zero);
                }
                if(priceProgram.getSecondIncome() == null){
                    priceProgram.setSecondIncome(zero);
                }
                if(priceProgram.getMemberIncome() == null){
                    priceProgram.setMemberIncome(zero);
                }
            });
            vo.setProductPriceProgramDetails(list);
        }else {
            // 没有id则新增查询spu表数据
            ProductSpu productSpu = new ProductSpu();
            if(condition.getBrandId() == null){
                throw new BusinessException(BusinessCode.CODE_880401);
            }
            logger.info("findProductPriceProgramDetail方法入参品牌id是" + condition.getBrandId());
            productSpu.setBrandId(condition.getBrandId());
            List<ProductSpu> productSpus = productSpuMapper.selectByModel(productSpu);
            List<ProductPriceProgramDetailVO> productPriceProgramDetails = new ArrayList<ProductPriceProgramDetailVO>();
            BigDecimal zero = BigDecimal.ZERO;
            productSpus.stream().forEach(spu ->{
                ProductPriceProgramDetailVO detailVO = new ProductPriceProgramDetailVO();
                detailVO.setId(spu.getId());
                detailVO.setSpuCode(spu.getSpuCode());
                detailVO.setSpuName(spu.getSpuName());
                if(spu.getGuidePrice() != null){
                    detailVO.setMarketPrice(spu.getGuidePrice());
                    detailVO.setSettlementPrice(spu.getGuidePrice());
                }
                detailVO.setFirstIncome(zero);
                detailVO.setFirstPoint(0);
                detailVO.setMemberIncome(zero);
                detailVO.setMemberPoint(0);
                detailVO.setSecondIncome(zero);
                detailVO.setSecondPoint(0);
                if(spu.getSaleStatus() != null){
                    detailVO.setSaleStatus(spu.getSaleStatus());
                }
                productPriceProgramDetails.add(detailVO);
            });
            vo.setProductPriceProgramDetails(productPriceProgramDetails);
        }
        return vo;
    }
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_COMMITTED)
    @Override
    public Integer deleteProductPriceProgram(Long id) {
        // 根据价格方案id查询该价格方案是否指定分销商使用
        DistributorChannelTypeCondition condition = new DistributorChannelTypeCondition();
        condition.setPriceTypeId(id);
        List<CustomerDistributorChannelTypeVO> channelTypeVOS = customerServiceClient.findDistributerChannelTypeList(condition).getDataWithException();
        if(!CollectionUtils.isEmpty(channelTypeVOS)){
            throw new BusinessException(BusinessCode.CODE_880100);
        }
        // 删除价格方案sku
        productPriceSkuMapper.deleteBypriceProgramId(id);
        // 删除价格方案spu
        productPriceSpuMapper.deleteBypriceProgramId(id);
        //删除价格方案
        return productPriceProgramMapper.deleteByPrimaryKey(id);
    }
    @Transactional(rollbackFor = {Exception.class},isolation = Isolation.READ_COMMITTED)
    @Override
    public void addProductPriceProgram(ProductPriceProgramAddCondition condition) {
        logger.info("addProductPriceProgram方法入参是：" + JsonUtil.toJSONString(condition));
        if (ObjectUtils.isEmpty(condition)){
            throw new BusinessException(BusinessCode.CODE_880703);
        }
        //校验spu集合是否为空
        if (CollectionUtils.isEmpty(condition.getProductPriceProgramAddDetailList())){
            logger.info("新增价格方案入参内的商品集合为空");
            throw new BusinessException(BusinessCode.CODE_880702);
        }
        //先校验此次修改的价格方案名称是否和别的价格方案名称重复
        Boolean ifUse = checkIfCanUsePriceName(condition);
        if (!ifUse){
            throw  new  BusinessException(BusinessCode.CODE_880701);
        }
        //先保存价格方案
        ProductPriceProgram productPriceProgram = new ProductPriceProgram();
        productPriceProgram.setCreatedBy(condition.getUserName());
        productPriceProgram.setModifiedBy(condition.getUserName());
        productPriceProgram.setBrandId(condition.getBrandId());
        productPriceProgram.setName(condition.getName());
        productPriceProgram.setCreatedTime(new Date());
        productPriceProgram.setBrandId(condition.getBrandId());
        productPriceProgram.setModifiedTime(new Date());
        //接到价格方案保存后的主键
        productPriceProgramMapper.insertSelective(productPriceProgram);
        //再保存spu
        for (ProductPriceProgramAddDetailCondition detail:condition.getProductPriceProgramAddDetailList()){
            ProductPriceSpu productPriceSpu = new ProductPriceSpu();
            productPriceSpu.setSpuId(detail.getId());
            productPriceSpu.setFirstIncome(detail.getFirstIncome());
            productPriceSpu.setFirstPoint(detail.getFirstPoint());
            productPriceSpu.setMemberIncome(detail.getMemberIncome());
            productPriceSpu.setMemberPoint(detail.getMemberPoint());
            productPriceSpu.setPriceProgramId(productPriceProgram.getId());
            productPriceSpu.setSecondIncome(detail.getSecondIncome());
            productPriceSpu.setSecondPoint(detail.getSecondPoint());
            productPriceSpu.setSettlementPrice(detail.getSettlementPrice());
            productPriceSpu.setBrandId(condition.getBrandId());
            productPriceSpu.setUniquePriceidSpuid(productPriceProgram.getId()+"_"+detail.getId());
            productPriceSpuMapper.insertSelective(productPriceSpu);
            //查询spu下的sku商品
            ProductSku productSku = new ProductSku();
            productSku.setSpuId(detail.getId());
            List<ProductSku> productSkus = productSkuMapper.selectByModel(productSku);
            if (CollectionUtils.isEmpty(productSkus)){
                continue;
            }
            //最后保存sku
            for (ProductSku ps:productSkus){
                ProductPriceSku productPriceSku = new ProductPriceSku();
                productPriceSku.setSpuId(detail.getId());
                productPriceSku.setSkuId(ps.getId());
                productPriceSku.setPriceProgramId(productPriceProgram.getId());
                productPriceSku.setBrandId(condition.getBrandId());
                productPriceSku.setFirstIncome(detail.getFirstIncome());
                productPriceSku.setFirstPoint(detail.getFirstPoint());
                productPriceSku.setMemberIncome(detail.getMemberIncome());
                productPriceSku.setMemberPoint(detail.getMemberPoint());
                productPriceSku.setSecondIncome(detail.getSecondIncome());
                productPriceSku.setSecondPoint(detail.getSecondPoint());
                productPriceSku.setBrandId(condition.getBrandId());
                productPriceSku.setSettlementPrice(detail.getSettlementPrice());
                productPriceSku.setUniquePriceidSpuidSkuid(productPriceProgram.getId()+"_"+detail.getId()+"_"+ps.getId());
                productPriceSkuMapper.insertSelective(productPriceSku);
            }
        }
    }

    @Override
    public void modifyProductPriceProgram(ProductPriceProgramAddCondition condition) {
        logger.info("modifyProductPriceProgram方法入参是：" + JsonUtil.toJSONString(condition));
        if (ObjectUtils.isEmpty(condition)){
            throw new BusinessException(BusinessCode.CODE_880703);
        }
        //先校验此次修改的价格方案名称是否和别的价格方案名称重复
        Boolean ifUse = checkIfCanUsePriceName(condition);
        if (!ifUse){
            throw  new  BusinessException(BusinessCode.CODE_880701);
        }
        //先修改价格方案
        ProductPriceProgram productPriceProgram = new ProductPriceProgram();
        productPriceProgram.setModifiedBy(condition.getUserName());
        productPriceProgram.setId(condition.getId());
        productPriceProgram.setBrandId(condition.getBrandId());
        productPriceProgram.setName(condition.getName());
        productPriceProgram.setModifiedTime(new Date());
        //修改价格方案
        productPriceProgramMapper.updateByPrimaryKeySelective(productPriceProgram);
        if (CollectionUtils.isEmpty(condition.getProductPriceProgramAddDetailList())){
            logger.info("修改价格方案入参内的商品集合为空");
            throw new BusinessException(BusinessCode.CODE_880702);
        }
        //再修改spu
        for (ProductPriceProgramAddDetailCondition detail:condition.getProductPriceProgramAddDetailList()){
            ProductPriceSpu ps = new ProductPriceSpu();
            ps.setPriceProgramId(condition.getId());
            ps.setSpuId(detail.getId());
            List<ProductPriceSpu> productPriceSpuList = productPriceSpuMapper.selectByModel(ps);
            if (CollectionUtils.isEmpty(productPriceSpuList)){
                continue;
            }
            ProductPriceSpu productPriceSpu = productPriceSpuList.get(0);
            productPriceSpu.setSpuId(detail.getId());
            productPriceSpu.setFirstIncome(detail.getFirstIncome());
            productPriceSpu.setFirstPoint(detail.getFirstPoint());
            productPriceSpu.setMemberIncome(detail.getMemberIncome());
            productPriceSpu.setMemberPoint(detail.getMemberPoint());
            productPriceSpu.setPriceProgramId(condition.getId());
            productPriceSpu.setSecondIncome(detail.getSecondIncome());
            productPriceSpu.setSecondPoint(detail.getSecondPoint());
            productPriceSpu.setSettlementPrice(detail.getSettlementPrice());
            productPriceSpuMapper.updateByPrimaryKeySelective(productPriceSpu);
            //查询spu下的sku商品
            ProductPriceSku productPriceSku = new ProductPriceSku();
            productPriceSku.setSpuId(detail.getId());
            productPriceSku.setPriceProgramId(condition.getId());
            List<ProductPriceSku> productPriceSkus = productPriceSkuMapper.selectByModel(productPriceSku);
            if (CollectionUtils.isEmpty(productPriceSkus)){
                logger.info("修改价格方案时，商品{}下无sku", productPriceSku.getSpuId());
                continue;
            }
            for (ProductPriceSku priceSku:productPriceSkus){
                priceSku.setFirstIncome(detail.getFirstIncome());
                priceSku.setFirstPoint(detail.getFirstPoint());
                priceSku.setMemberIncome(detail.getMemberIncome());
                priceSku.setMemberPoint(detail.getMemberPoint());
                priceSku.setSecondIncome(detail.getSecondIncome());
                priceSku.setSecondPoint(detail.getSecondPoint());
                priceSku.setSettlementPrice(detail.getSettlementPrice());
                productPriceSkuMapper.updateByPrimaryKeySelective(priceSku);
            }
        }
    }

    private Boolean checkIfCanUsePriceName(ProductPriceProgramAddCondition condition) {
        List<ProductPriceProgram> productPriceProgramList = productPriceProgramMapper.checkPriceProgramName(condition.getName());
        if (productPriceProgramList.size() == 0){
            return true;
        }else if (productPriceProgramList.size() == 1 && (productPriceProgramList.get(0).getId().equals(condition.getId()))){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 查询价格方案列表(不带分页)
     * @param condition
     * @return
     */
    @Override
    public List<ProductPriceProgram> findProductPriceProgramListByModel(ProductPriceProgramCondition condition) {
        ProductPriceProgram productPriceProgram = new ProductPriceProgram();
        BeanUtils.copyProperties(condition, productPriceProgram);
        return    productPriceProgramMapper.selectByModel(productPriceProgram);
    }

    @Override
    public Boolean checkPriceProgramName(String name) {
        List<ProductPriceProgram> productPriceProgramList = productPriceProgramMapper.checkPriceProgramName(name);
        if (productPriceProgramList.size() == 0){
            return true;
        }else {
            return false;
        }

    }
}
